package com.taxshare.purchaser.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.taxshare.mybatis.pager.PageHelp;
import com.taxshare.mybatis.pager.PageRequest;
import com.taxshare.purchaser.constant.CodeConstant;
import com.taxshare.purchaser.entity.*;
import com.taxshare.purchaser.mapper.ApplicationRecordDetailMapper;
import com.taxshare.purchaser.mapper.ApplicationRecordMapper;
import com.taxshare.purchaser.mapper.PlaneTicketMapper;
import com.taxshare.purchaser.mapper.PlaneTicketPoolMapper;
import com.taxshare.purchaser.view.dto.PlaneTicketDTO;
import com.taxshare.response.beans.Response;
import com.taxshare.tools.token.UserInfoUtil;
import com.taxshare.tools.util.UUIDUitl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author YANG
 * @date 2021/4/9
 * @Description:飞机客票行程单采集
 */
@Slf4j
@Service
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED)
public class PlaneTicketCollectService extends ServiceImpl<PlaneTicketMapper, PlaneTicketEntity> {

    private static String timeStart = " 00:00:00";
    private static String timeEnd = " 23:59:59";

    @Autowired
    PlaneTicketDetailService planeTicketDetailService;

    @Autowired
    PlaneTicketPoolMapper planeTicketPoolMapper;

    @Autowired
    ApplicationRecordDetailMapper applicationRecordDetailMapper;

    @Autowired
    ApplicationRecordMapper applicationRecordMapper;

    /**
     * 飞机客票行程单查询【发票采集】
     *
     * @param query
     * @return
     */
    public Response queryPlaneTicket(PageRequest<PlaneTicketDTO> query) {
        QueryWrapper<PlaneTicketEntity> planeQuery = new QueryWrapper<>();
        PlaneTicketDTO planeTicketDTO = query.getInfo();
        String createTimeStrStart = planeTicketDTO.getCreateTimeStrStart();
        String createTimeStrEnd = planeTicketDTO.getCreateTimeStrEnd();
        String selectFlag = planeTicketDTO.getSelectFlag();
        if (StrUtil.isNotBlank(planeTicketDTO.getTicketNo())) {
            planeQuery.eq("ticket_no", planeTicketDTO.getTicketNo());
        }
        if (StrUtil.isNotBlank(createTimeStrStart) && StrUtil.isNotBlank(createTimeStrEnd)) {
            planeQuery.between("create_time_str", createTimeStrStart + timeStart, createTimeStrEnd + timeEnd);
        }
        //权限处理
        if(StrUtil.isNotBlank(UserInfoUtil.getUserID())){
            if(CodeConstant.GENERAL_TYPE.equals(UserInfoUtil.getUserType())){
                planeQuery.and((invoice ->
                        invoice.eq("person_liable_id", UserInfoUtil.getUserID())//责任人
                            .or().eq("collector_id", UserInfoUtil.getUserID())//采集人
                                .or().like("licensee_id", UserInfoUtil.getUserID())));//被授权人
            }
        }
        //查询页面判断标志 采集页面查询传1，未报销传2，已报销传3
        if (StrUtil.isNotBlank(selectFlag)) {
            if (CodeConstant.FLAG_WBX.equals(selectFlag)) {
                planeQuery.in("reimbursement_status", CodeConstant.NOT_REIMBURSEMENT);
            } else if (CodeConstant.FLAG_YBX.equals(selectFlag)) {
                planeQuery.eq("reimbursement_status", CodeConstant.REIMBURSEMENT_2);
            } else if (CodeConstant.FLAG_FPCJ.equals(selectFlag)) {
                if (StrUtil.isNotBlank(planeTicketDTO.getReimbursementStatus())) {
                    planeQuery.eq("reimbursement_status", planeTicketDTO.getReimbursementStatus());
                }
            }
        } else {
            return Response.error("PUR_107");
        }
        planeQuery.orderByDesc("create_time");
        IPage<PlaneTicketEntity> planeTicketEntityIPage = PageHelp.siamplePage(this, planeQuery, query.getPage(), PlaneTicketEntity.class);
        return Response.success(planeTicketEntityIPage);
    }

    /**
     * 飞机客票行程单航班信息查询【发票采集】
     *
     * @param query
     * @return
     */
    public Response queryPlaneTicketDetail(PageRequest<PlaneTicketDTO> query) {
        QueryWrapper<PlaneTicketDetailEntity> planedetailQuery = new QueryWrapper<>();
        PlaneTicketDTO planeTicketDTO = query.getInfo();
        String uuid = planeTicketDTO.getUuid();
        planedetailQuery.eq("link_id", uuid);
        planedetailQuery.orderByDesc("create_time");
        IPage<PlaneTicketDetailEntity> planeTicketDetailEntityIPage = PageHelp.siamplePage(planeTicketDetailService, planedetailQuery, query.getPage(), PlaneTicketDetailEntity.class);
        return Response.success(planeTicketDetailEntityIPage);
    }

    /**
     * 飞机客票行程单删除【发票采集】
     *
     * @param planeTicketDTO
     * @return
     */
    public Response planeTickeDelete(PlaneTicketDTO planeTicketDTO) {
        List<String> uuidList = planeTicketDTO.getUuidList();
        if (CollUtil.isNotEmpty(uuidList)) {
            QueryWrapper<PlaneTicketEntity> planeQuery = new QueryWrapper<>();
            planeQuery.in("uuid", uuidList);
            planeQuery.eq("reimbursement_status", CodeConstant.REIMBURSEMENT_2);
            if (baseMapper.selectCount(planeQuery) > 0) {
                return Response.error("PUR_103");
            }
            baseMapper.delete(new QueryWrapper<PlaneTicketEntity>().in("uuid", uuidList));
            planeTicketDetailService.remove(new QueryWrapper<PlaneTicketDetailEntity>().in("link_id", uuidList));
        } else {
            return Response.error("PUR_201");
        }
        return Response.success();
    }

    /**
     * 责任人、记账科目、授权报销设置【未报销】
     *
     * @param planeTicketDTO
     * @return
     */
    public Response personLiable(PlaneTicketDTO planeTicketDTO) {
        String updateFlag = planeTicketDTO.getUpdateFlag();
        PlaneTicketEntity planeTicketEntity = new PlaneTicketEntity();
        if (StrUtil.isNotBlank(updateFlag)) {
            //责任人设置
            if (CodeConstant.FLAG_ZRR.equals(updateFlag)) {
                planeTicketEntity.setPersonLiable(planeTicketDTO.getPersonLiable());
                planeTicketEntity.setPersonLiableId(planeTicketDTO.getPersonLiableId());
            } else if (CodeConstant.FLAG_JZKM.equals(updateFlag)) {
                //记账科目设置
                planeTicketEntity.setBookingAccount(planeTicketDTO.getBookingAccount());
            } else if (CodeConstant.FLAG_SQR.equals(updateFlag)) {
                //被授权人设置
                List<String> licenseeList = planeTicketDTO.getLicenseeList();
                List<String> licenseeIdList = planeTicketDTO.getLicenseeIdList();
                if (CollUtil.isNotEmpty(licenseeList) && CollUtil.isNotEmpty(licenseeIdList)) {
                    String licensee = licenseeList.stream().map(String::valueOf).collect(Collectors.joining(","));
                    String licenseeId = licenseeIdList.stream().map(String::valueOf).collect(Collectors.joining(","));
                    planeTicketEntity.setLicensee(licensee);
                    planeTicketEntity.setLicenseeId(licenseeId);
                } else {
                    return Response.error("PUR_112");
                }
            }
            UpdateWrapper<PlaneTicketEntity> planeUpdate = new UpdateWrapper<>();
            planeUpdate.in("uuid", planeTicketDTO.getUuidList());
            this.update(planeTicketEntity, planeUpdate);
        } else {
            return Response.error("PUR_107");
        }
        return Response.success();
    }

    /**
     * 提交报销【未报销】
     *
     * @param planeTicketDTO
     * @return
     */
    public Response submitReimbursement(PlaneTicketDTO planeTicketDTO) {
        QueryWrapper<PlaneTicketEntity> planeQuery = new QueryWrapper<>();
        List<String> uuidList = planeTicketDTO.getUuidList();
        planeQuery.in("uuid", uuidList);
        planeQuery.in("reimbursement_status", CodeConstant.NOT_REIMBURSEMENT);
        List<PlaneTicketEntity> planeTicketEntities = baseMapper.selectList(planeQuery);
        if (planeTicketEntities == null || planeTicketEntities.isEmpty() || uuidList.size() != planeTicketEntities.size()) {
            return Response.error("PUR_105");
        }
        for (PlaneTicketEntity planeTicketEntity : planeTicketEntities) {
            PlaneTicketPoolEntity planeTicketPoolEntity = new PlaneTicketPoolEntity();
            BeanUtil.copyProperties(planeTicketEntity, planeTicketPoolEntity);
            planeTicketPoolEntity.setUuid(UUIDUitl.UUID32(false));
            planeTicketPoolEntity.setReimbursementStatus(CodeConstant.REIMBURSEMENT_2);
            planeTicketPoolMapper.insert(planeTicketPoolEntity);
        }
        //将飞机客票行程单采集表中对应发票的报销状态改为已报销
        planeTicketEntities.forEach(planeTicketEntity -> {
            planeTicketEntity.setReimbursementStatus(CodeConstant.REIMBURSEMENT_2);
            planeTicketEntity.setSubmitUserId(UserInfoUtil.getUserID());
        });
        this.updateBatchById(planeTicketEntities);
        return Response.success();
    }

    /**
     * 申请驳回【已报销】
     *
     * @param planeTicketDTO
     * @return
     */
    public Response applicationRejected(PlaneTicketDTO planeTicketDTO) {
        List<String> uuidList = planeTicketDTO.getUuidList();
        List<PlaneTicketEntity> planeTicketEntities = baseMapper.selectList(new QueryWrapper<PlaneTicketEntity>().in("uuid", uuidList));
        if (planeTicketEntities == null || planeTicketEntities.isEmpty() || uuidList.size() != planeTicketEntities.size()) {
            return Response.error("PUR_110");
        }
        //生成申请单号
        String recordNo = UUIDUitl.UUID16(false);
        for (PlaneTicketEntity planeTicketEntity : planeTicketEntities) {
            ApplicationRecordDetailEntity applicationRecordDetailEntity = new ApplicationRecordDetailEntity();
            applicationRecordDetailEntity.setUuid(UUIDUitl.UUID32(false));
            applicationRecordDetailEntity.setRecordNo(recordNo);
            applicationRecordDetailEntity.setInvoiceType(planeTicketEntity.getInvoiceType());
            applicationRecordDetailEntity.setInvoiceNo(planeTicketEntity.getTicketNo());
            applicationRecordDetailMapper.insert(applicationRecordDetailEntity);
        }
        ApplicationRecordEntity applicationRecordEntity = new ApplicationRecordEntity();
        applicationRecordEntity.setUuid(UUIDUitl.UUID32(false));
        applicationRecordEntity.setRecordNo(recordNo);
        applicationRecordEntity.setApplicationDate(planeTicketDTO.getApplicationDate());
        applicationRecordEntity.setApplicationReasons(planeTicketDTO.getApplicationReasons());
        applicationRecordEntity.setApplicationPerson(UserInfoUtil.getUserNickName());
        applicationRecordEntity.setApprovalStatus(CodeConstant.APPROVAL_1);
        applicationRecordEntity.setTicketTypes(CodeConstant.TICKET_FJP);
        applicationRecordMapper.insert(applicationRecordEntity);
        planeTicketEntities.forEach(planeTicketEntity -> {
            planeTicketEntity.setProcedureStatus(CodeConstant.APPROVAL_5);
        });
        this.updateBatchById(planeTicketEntities);
        return Response.success();
    }
}
